package com.matto1990.app.madlab.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.matto1990.app.madlab.R;
import com.matto1990.app.madlab.provider.MadlabContract.Events;
import com.matto1990.app.madlab.provider.MadlabContract.Meetups;
import com.matto1990.app.madlab.util.NotifyingAsyncQueryHandler;
import com.matto1990.app.madlab.util.TitlebarActivity;
import com.matto1990.app.madlab.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class MeetupDetailActivity extends TitlebarActivity implements AsyncQueryListener {
    private static final String TAG = "Madlab";
    
    private NotifyingAsyncQueryHandler handler;
    
    private TextView eventTitle;
    private TextView meetupTitle;
    private TextView meetupDescription;
    private TextView meetupDescriptionTitle;
    private TextView meetupAttending;
    private Button meetupAttendingButton;
    private TextView startDateMonth;
    private TextView startDateDay;
    
    private Uri meetupUri;
    private Cursor meetupCursor;
    
    private Date today;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Set the layout
        setContentView(R.layout.activity_meetup_detail);
        
        // Setup the title bar UI
        setupTitlebar();
        
        // Setup a data object for the start of today
        today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setMinutes(0);
        
        // Get the views
        eventTitle = (TextView) findViewById(R.id.event_title);
        meetupTitle = (TextView) findViewById(R.id.meetup_title);
        meetupDescription = (TextView) findViewById(R.id.meetup_description);
        meetupDescriptionTitle = (TextView) findViewById(R.id.meetup_description_title);
        meetupAttending = (TextView) findViewById(R.id.meetup_attending);
        meetupAttendingButton = (Button) findViewById(R.id.meetup_btn_attending);
        startDateMonth = (TextView) findViewById(R.id.meetup_start_date_month);
        startDateDay = (TextView) findViewById(R.id.meetup_start_date_day);
        
        // Setup the attending button
        meetupAttendingButton.setOnClickListener(attendingListener);
        
        // TODO: Set the event detials click
        
        // Get the application context and content uris
        final Intent intent = getIntent();
        meetupUri = intent.getData();
        
        // Start background query to load events
        handler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
        handler.startQuery(meetupUri, MeetupQuery.PROJECTION);
    }
    
    @Override
    public void onQueryComplete(int token, Object cookie, Cursor cursor) {
        meetupCursor = cursor;
        
        if (cursor.getCount() > 0) {
            // Move to the first (and only) position
            cursor.moveToFirst();
            
            // Set the event title
            eventTitle.setText(cursor.getString(cursor.getColumnIndex(Events.EVENT_TITLE)));
            
            // Set the optional meetup title
            final String title = cursor.getString(cursor.getColumnIndex(Meetups.MEETUP_TITLE));
            if (title != null) {
                meetupTitle.setVisibility(View.VISIBLE);
                meetupTitle.setText(title);
            }
            else {
                meetupTitle.setVisibility(View.GONE);
            }
            
            // Set the meetup date
            // Setup some date formats
            final SimpleDateFormat sqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final SimpleDateFormat monthDateFormat = new SimpleDateFormat("MMM yy");
            final SimpleDateFormat dayDateFormat = new SimpleDateFormat("dd");
            
            try {
                // Setup the nice date text
                final String startDate = cursor.getString(cursor.getColumnIndex(Meetups.MEETUP_START_DATETIME));
                
                // Set the view contents
                startDateMonth.setText(monthDateFormat.format(sqlDateFormat.parse(startDate)));
                if (sqlDateFormat.parse(startDate).before(today)) {
                    startDateMonth.setBackgroundColor(R.color.title_background);
                }
                startDateDay.setText(dayDateFormat.format(sqlDateFormat.parse(startDate)));
            } catch (ParseException e) {
                Log.w(TAG, "Incorrect date format", e);
            }
            
            // Set the interested text
            final boolean attending = cursor.getInt(cursor.getColumnIndex(Meetups.MEETUP_ATTENDING)) == 1;
            String attendingText;
            if (attending) {
                attendingText = "You are arrending";
            }
            else {
                attendingText = "You are not attending";
            }
            meetupAttending.setText(attendingText);
            
            // Set the optional meetup description
            final String description = cursor.getString(cursor.getColumnIndex(Meetups.MEETUP_DESCRIPTION));
            if (description != null) {
                meetupDescription.setVisibility(View.VISIBLE);
                meetupDescriptionTitle.setVisibility(View.VISIBLE);
                meetupDescription.setText(description);
            }
            else {
                meetupDescription.setVisibility(View.GONE);
                meetupDescriptionTitle.setVisibility(View.GONE);
            }
        }
        else {
            // TODO: Handle this properly
            Log.w(TAG, "Unknown meetupid: " + Meetups.getMeetupId(meetupUri));
        }
    }
    
    private OnClickListener attendingListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            meetupCursor.moveToFirst();
            
            // Get the current value of interested
            final boolean attending = meetupCursor.getInt(meetupCursor.getColumnIndex(Meetups.MEETUP_ATTENDING)) == 1;
            
            // Set up a content values to change it to the opposite
            final ContentValues values = new ContentValues();
            values.put(Meetups.MEETUP_ATTENDING, !attending);
            
            // Make the change
            getContentResolver().update(meetupUri, values, null, null);
            
            Log.i("Madlab", "Updated attending");
            
            // Requery
            handler.startQuery(meetupUri, MeetupQuery.PROJECTION);
        }
    };
    
    /** {@link Meetup} query parameters. */
    private interface MeetupQuery {
        String[] PROJECTION = {
                "meetups." + BaseColumns._ID,
                Meetups.MEETUP_ID,
                Meetups.MEETUP_TITLE,
                "meetups." + Meetups.MEETUP_DESCRIPTION,
                Meetups.MEETUP_START_DATETIME,
                Meetups.MEETUP_ATTENDING,
                Events.EVENT_TITLE
        };
    }
}
